<!--
 * @Description: 敏感文字 展示隐藏
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 04/09/24 PM12:55
 -->
<!--setup-->
<script setup lang="ts">
import { onMounted, getCurrentInstance, computed, ref, type ComponentInternalInstance, type PropType } from 'vue'
import { toStarShow } from '@shared/utils/secure'
import SvgIcon from '@/components/svg-icon/index.vue'
import desensitizeString from '@/components/sensitive-text/desensitize-string'
import { to } from 'sf-utils2'
import { ElMessage } from 'element-plus'
import cfLogApi from '@/api/modules/cf-log' // Api

defineOptions({
  name: 'SensitiveText'
})
const { proxy } = getCurrentInstance() as ComponentInternalInstance

const props = defineProps({
  /**
   * 文本
   */
  text: {
    type: String,
    default: ''
  },

  /**
   * 敏感类型
   */
  type: {
    type: String as PropType<'mobile' | 'idcard' | 'name' | 'email' | 'guarantorName' | 'guarantorOrgName'>,
    default: 'idcard'
  },

  /**
   * 对象，用于添加自定义字段
   */
  obj: {
    type: Object,
    default: () => {}
  },

  /**
   * 默认值
   */
  defaultValue: {
    type: String,
    default: '-'
  }
})
const emit = defineEmits({})

/* 状态 */

const isShowStar = ref(true) // 是否显示星号, 默认是true

/* 方法 */

/**
 * 切换star
 */
function onSwitchStar() {
  if (isShowStar.value && props.type === 'idcard') {
    saveSensitiveOperate() // 保存敏感操作
  }
  isShowStar.value = !isShowStar.value // 切换显隐
}

/*
 * 传递债务人ID
 * @returns Promise<void>
 */
async function saveSensitiveOperate () {
  const [res, err] = await to(cfLogApi.cfSaveSensitiveOperate({ id: props.obj.obligorId }))
  if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
}

/* 计算 */

/**
 * 文本内容
 */
const _text = computed(() => {
  return isShowStar.value ? desensitizeString(props.text, props.type) : props.text
})

/* 监听 */

/* 周期 */
onMounted(() => {
  // console.log(toStarShow(props.text, props.type, props.defaultValue))
  console.log('toStarShow', toStarShow('320723199503074252', 'idcard', '-'))
})

/* 暴露 */
defineExpose({
  $: proxy.$,
  isShowStar
})
</script>

<!--render-->
<template>
  <span class="sensitive-text">
    <span class="sensitive-text__content">
      <slot
        name="text"
        v-bind="{ isShowStar }"
      >
        {{ _text ?? '-' }}
      </slot>
    </span>

    <span
      v-if="props.text"
      class="sensitive-text__suffix pl-8px cursor-pointer"
      @click="onSwitchStar"
    >
      <slot name="suffix">
        <SvgIcon
          v-if="isShowStar"
          size="14px"
          svg="common/eye-hidden"
        />
        <SvgIcon
          v-else
          size="14px"
          svg="common/eye-show"
        />
      </slot>
    </span>
  </span>
</template>

<!--style-->
<style scoped lang="less">
.sensitive-text {
  display: inline-flex;
  align-items: center;
}
</style>
